package com.sky.service.admin.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersConfirmDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersRejectionDTO;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.OrdersCancelException;
import com.sky.mapper.admin.AdminOrderMapper;
import com.sky.mapper.user.OrderDetailMapper;
import com.sky.mapper.user.OrderMapper;
import com.sky.pojo.OrderDetail;
import com.sky.pojo.Orders;
import com.sky.result.PageResult;
import com.sky.service.admin.AdminOrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderVO;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AdminOrderServiceImpl implements AdminOrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;



    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());

        Page<Orders> page=orderMapper.ordersPageQuery(ordersPageQueryDTO);

        // 部分订单状态，需要额外返回订单菜品信息
        List<OrderVO> orderVOList = getOrderVOList(page);

        return new PageResult(page.getTotal(),orderVOList);
    }

    /**
     * 统计订单数量
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        Integer status2=orderMapper.countStatus(Orders.TO_BE_CONFIRMED);//待商家接单
        Integer status3=orderMapper.countStatus(Orders.CONFIRMED);//待骑手接单
        Integer status5=orderMapper.countStatus(Orders.TOBEDELIVERED);//待送达

        OrderStatisticsVO orderStatisticsVO=new OrderStatisticsVO();
        orderStatisticsVO.setWaitng4RiderReceiveOrders(status3);//待骑手接单
        orderStatisticsVO.setWaiting4MerchantReceiveOrders(status2);//到商家接单
        orderStatisticsVO.setToBeArrivedOrders(status5);//到商家接单


        return orderStatisticsVO;
    }

    @Override
    public OrderVO details(Long id) {
        Orders orders = orderMapper.getById(id);
        //根据这个id,去订单详情表里面查
        Long ordersId = orders.getId();
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(ordersId);
        OrderVO orderVO=new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }

    /**
     * 商家接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        //商家接单后,将状态改为3
        Orders orders=new Orders();
        orders.setId(ordersConfirmDTO.getId());
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);

    }

    /**
     * 商家拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {

        //只有订单状态=2,才能拒单
        Orders orderDB=orderMapper.getById(ordersRejectionDTO.getId());
        if (orderDB==null  || !orderDB.getStatus().equals(Orders.REFUND)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }


        Orders orders = new Orders();
        orders.setId(ordersRejectionDTO.getId());
        orders.setStatus(Orders.CANCELLED_ORDER);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }


    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orderDB = orderMapper.getById(ordersCancelDTO.getId());

        //如果已支付,商家不能主动取消
        if (orderDB==null  || orderDB.getPayStatus().equals(Orders.PAID)){

            throw new OrdersCancelException(MessageConstant.ORDER_NOT_CANCEL);

        }

        Orders orders=new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED_ORDER);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);

    }


    /**
     * 派单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orderDB = orderMapper.getById(id);

        //- 派送订单其实就是将订单状态修改为“派送中”
        //- 只有状态为“待派送”的订单可以执行派送订单操作
        if (orderDB==null  || !orderDB.getPayStatus().equals(Orders.CONFIRMED)){

            throw new OrderBusinessException(MessageConstant.ORDER_DISPATCH_ERROR);
        }
        Orders orders=new Orders();
        orders.setId(orderDB.getId());
        orders.setStatus(Orders.TOBEDELIVERED);
        orderMapper.update(orders);



    }


    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orderDB = orderMapper.getById(id);

        //- - 完成订单其实就是将订单状态修改为“已完成”
        //- 只有状态为“派送中”的订单可以执行订单完成操作
        if (orderDB==null  || !orderDB.getPayStatus().equals(Orders.TOBEDELIVERED)){

            throw new OrderBusinessException(MessageConstant.ORDER_COMPLETE_ERROR);
        }
        Orders orders=new Orders();
        orders.setId(orderDB.getId());
        orders.setStatus(Orders.COMPLETE_ORDER);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);

    }


    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        List<OrderVO> orderVOList = new ArrayList<>();
        List<Orders> orderList = page.getResult();
        if (!CollectionUtils.isEmpty(orderList)){
            for (Orders orders : orderList) {
                OrderVO orderVO=new OrderVO();
                BeanUtils.copyProperties(orders,orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;

    }

    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 创建一个用于存储转换后的字符串的列表
        List<String> orderDishList = new ArrayList<>();

        // 遍历订单详情列表，并将每个订单详情对象的信息拼接为字符串
        for (OrderDetail orderDetail : orderDetailList) {
            String orderDish = orderDetail.getName() + "*" + orderDetail.getNumber() + ";";
            orderDishList.add(orderDish);
        }

        // 将该订单对应的所有菜品信息拼接在一起
        StringBuilder result = new StringBuilder();
        for (String dishStr : orderDishList) {
            result.append(dishStr);
        }

        return result.toString();
    }




}
